package com.chain.BrotherExchange.viewmodel;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;

import com.chain.BrotherExchange.data.DataRepository;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.UserInfo;
import com.chain.BrotherExchange.data.model.UserLogin;
import com.chain.BrotherExchange.utils.Androids;

public class LoginViewModel extends AndroidViewModel {

    private MutableLiveData<Resource<UserInfo.DataBeanX>> mLoginLiveData;

    public LoginViewModel(@NonNull Application application) {
        super(application);
        this.mLoginLiveData = new MutableLiveData<>();
    }

    public MutableLiveData<Resource<UserInfo.DataBeanX>> login(String mobilePhone, String password) {
        if (VerificationManage.verifyPasswordAndMobile(mobilePhone, password)){
            mLoginLiveData.setValue(Resource.loading());
            DataRepository.get().login(mobilePhone, password, result -> {
                UserLogin.DataBeanX resultData = result.getData();
                if (result.isSucceed() && resultData != null) {
                    requestUserInfo(resultData.getDataX().getToken(), resultData.getDataX().getUid());
                } else {
                    mLoginLiveData.setValue(Resource.error(result.getMsg()));
                }
            });
        }

        return mLoginLiveData;
    }

    private void requestUserInfo(String token, int uid) {
        DataRepository.get().userInfo(token, uid, userInfo -> {
            UserInfo.DataBeanX userInfoData = userInfo.getData();
            if (userInfo.isSucceed() && userInfoData != null) {
                // 本地登录状态保存
                String country = userInfoData.getDataX().getCountry(); // 区号
                Androids.LocalConfig.login(token, uid, userInfoData.getDataX().getPhone(), country);
                Androids.LocalConfig.setAlreadySetTransactionPassword(userInfoData.getDataX().isPay_switch());
                mLoginLiveData.setValue(Resource.success(userInfoData));
            } else {
                mLoginLiveData.setValue(Resource.error(userInfo.getMsg()));
            }
        });
    }
}
